#coding=utf-8

require "aio/core"

class Aio::Module::InputStyle::XinhuaNat < Aio::Module::InputStyle
	include Aio::Module

	Xinhua_Routing = /^------------------------------------------------------------$/

	def initialize
		super({
			:author				=> "Elin",
			:description	=> "这个模块专门针对中行网络标准化管理NAT软件",
			:platform			=> "ausware",
			:file_suffix	=> Regexp.new('\.diag$'),
			:pass_file		=> [
							Regexp.new('RoutingTable.*'),
							Regexp.new('路由状态'),
						]
		})
	end

	def parse
		# dir 为 Pathname 类
		dir = self.input_file
		
		# 分析第一层： 文件夹名称包含设备名称+管理IP
		::Dir.foreach(dir) do |device_layer|
			if device_layer.downcase == "." or device_layer.downcase == ".."
				next
			end

			tmp = []
			device_layer.reverse.split('_', 2).each do |res|
				tmp << res.reverse
			end

			manager_ip  = tmp[0]
			device_name = tmp[1]


			# 分析第二层：文件后缀为.diag，此外还有个HSRP文件夹，但是可有一次搞定
			Find.find(File.join(dir, device_layer)) do |context_layer|

				# 如果文件后缀名不是.diag则跳过
				if ! self.file_suffix?(context_layer)
					next
				end

				# 检查是否是需要略过的文件
				if self.pass_file?(context_layer)
					next
				end

				fo = File.open(context_layer, "r+", :encoding => "utf-8")
				context = fo.each_line.to_a

				# 分割输出，在路由状态中会有这种情况
				split(context, Xinhua_Routing).each do |cont|
					cmd = cont.shift.strip
					yield device_name, cmd, cont, manager_ip
				end
			end
		end
	end

	def split(array, pattern)
		Aio::Base::Toolkit::Array.split(array, pattern)
	end
end
